package kisti.module.tierServer;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import kisti.module.log.Glog;



/**
 * 
 * <pre>
 * kisti.module.tierServer
 *   |_ CeMonGraph.java
 *
 * </pre>
 *
 * Desc : ce02의 그래프 이미지를 가져온다
 * @Company : KISTI
 * @Author :daniel
 * @Date   :2011. 11. 14. 오후 5:47:52
 * @Version: V1
 *
 */
public class CeMonGraph {


	
	
	public CeMonGraph() {
		// TODO Auto-generated constructor stub
	}
	
	
	/**
	 * 
	 * Desc : pbsmon으로부터 페이지 정보를 다운로드 하고 
	 * 그래프 이미지 URL만 축출한다. 
	 * @Method Name : getImageUrl
	 * @param psbURL
	 * @return 다운로드할 그래프 이미지 URL을 반환
	 *
	 */
	public String getImageUrl(String psbURL){		
		String imgUrl ="http://vobox02.sdfarm.kr/pbswebmon/pbswebmon-ce03/graph/";		
		
		
		try {
			Glog.Log(Glog.LOG_COMMON,"getImageUrl" ,"---------- get Image URL..   ------------ ");
			Glog.Log(Glog.LOG_COMMON,"getImageUrl" ,"imgURL: "+imgUrl);
			URL url = new URL(psbURL);
				
			FileOutputStream fos = null;
			BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

		
			String contents ="";
			String tmp;
			
			while((tmp = in.readLine()) != null){	
				contents += tmp;
			}
			
			int startIdx = contents.indexOf("graph/");
			int endIdx = contents.indexOf("</img>");			
			String imgName = contents.substring(startIdx+6, endIdx-1);			
			
			imgUrl += imgName;
			
		}catch(Exception e){		
			Glog.Log(Glog.LOG_ERROR,"getImageUrl" , e.toString());	
		}		
		return imgUrl;
	}
	
	
	/**
	 * 
	 * Desc : 그래프 이미지를 다운로드 한다. 
	 * @Method Name : downloadImage
	 * @param imgUrl
	 * @param saveFileName
	 * @return 이미지가 다운되었는지 여부를 boolean 형태로 반환 true: 이미지 저장 완료 , false: 이미지 저장 실패
	 *
	 */
	public Boolean downloadImage(String imgUrl, String saveFileName){
		Boolean isSaved = false;
		
		URL url = null;
		URLConnection urlConnection = null;
		try {
			Glog.Log(Glog.LOG_COMMON,"downloadImage" ,"---------- download ce02 graph Image    ------------ ");
			url = new URL(imgUrl);

			InputStream is = url.openStream();
			FileOutputStream fos = new FileOutputStream(saveFileName);
			
			byte[] buffer = new byte[1024];
			int readSize = 0;
			while ((readSize = is.read(buffer)) > 0 ) {
				fos.write(buffer, 0, readSize);
			}			
			Glog.Log(Glog.LOG_COMMON,"downloadImage" ,"graph image saved...");
			
			
			fos.close();
			is.close();
			
			isSaved = true;			
		} catch (Exception e) {
			// TODO: handle exception
			Glog.Log(Glog.LOG_ERROR,"getImageUrl" , e.toString());			
		}		
		return isSaved;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	/**
	 * Desc :
	 * @Method Name : main
	 * @param args
	 * 
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
	}
}
